import Taro, {Component} from '@tarojs/taro'
import {View, Text, Input, Textarea, Picker, Button} from '@tarojs/components'
import {connect} from '@tarojs/redux'
import {createTopic, updateTopic} from '../../actions/topic'

import './publish.scss'

@connect((store) => {
  return {cateData: store.menu.cateData, ...store.user, topicInfo: store.topicList.topicInfo }
})

class Publish extends Component {
  state = {
    cur_Cate: null,
    title: null,
    content: null,
    isEdit: false
  }
  componentWillMount () {
    const {edit} = this.$router.params
    let {topicInfo} = this.props
    this.setState({
      isEdit: edit == '1',
      title: edit == '1' && topicInfo ? topicInfo.title : '',
      content: edit == '1' && topicInfo ? topicInfo.content : '',
      topicid: edit == '1' && topicInfo ? topicInfo.id : ''
    })
  }
  changeVal (e) {
    let {cateData} = this.props
    this.setState({
      cur_Cate: cateData[e.target.value]
    })
  }
  changeTitle (e) {
    console.log(this);
    this.setState({
      title: e.target.value
    })
  }
  changeText (e) {
    this.setState({
      content: e.target.value
    })
  }
  submitTopic () {
    let {title, content, cur_Cate, isEdit, topicid} = this.state
    let {accessToken} = this.props
    if(title && content && cur_Cate) {
      let params = {tab: 'dev', title, content, accesstoken: accessToken}
      if(isEdit) {
        params['topicid'] = topicid
        updateTopic(params).then(res => {
          if(res) {
            Taro.navigateBack()
          }
        })
      }else{
        createTopic(params).then(res => {
          if(res) {
            Taro.navigateBack()
          }
        })
      }
    }else{
      Taro.showToast({title: '不能为空', icon: 'none'})
    }
  }
  render () {
    let {cur_Cate, title, content} = this.state
    return (
      <View className='publish-wrap'>
        <Picker mode='selector' range={this.props.cateData} rangeKey='value' onChange={this.changeVal.bind(this)}>
          <View className='sel-wrap'>{cur_Cate ? cur_Cate.value : ''}</View>
        </Picker>
        <Input value={title} onInput={this.changeTitle.bind(this)} placeholder='标题'/>
        <Textarea value={content} onInput={this.changeText.bind(this)} placeholder='内容' />
        <Button onClick={this.submitTopic.bind(this)}>submit</Button>
      </View>
    )
  }
}

export default Publish